﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System;
using System.Reflection;
using Newtonsoft.Json;

public class AssetsImporter : AssetPostprocessor
{
    private const string SettingPath = "Assets/Scripts/Editor/AssetPostprocessor/ImporterSetting.json";


    private static AssetsImportSetting AssetsImportSettings = null;
    private static Dictionary<string,PropertyInfo> TextureImporterProperties;
    [Serializable]
    public class AssetsImportSetting
    {
        [SerializeField]
        public AssetsImportSettingItem[] TextureSettings;
    }

    [Serializable]
    public class AssetsImportSettingItem
    {
        [SerializeField]
        public string PathRegex;
        [SerializeField]
        public Dictionary<string, string> Settings;
    }
    private void OnPreprocessTexture()
    {
        if (AssetsImportSettings == null)
        {
            var str = File.ReadAllText(SettingPath);
            if (string.IsNullOrEmpty(str))
            {
                //Debug.LogError("[AssetsImporter] OnPreprocessTexture 配置文件无效:" + SettingPath);
                return;                    
             }
            AssetsImportSettings = JsonConvert.DeserializeObject<AssetsImportSetting>(str);
            if (AssetsImportSettings == null)
            {
                //Debug.LogError("[AssetsImporter] OnPreprocessTexture 配置文件无效:" + SettingPath);
                return;
            }
            //缓存每个Property
            Type type = typeof(TextureImporter);
            var ps = type.GetProperties();
            TextureImporterProperties = new Dictionary<string, PropertyInfo>();
            for (int i = 0; i < ps.Length; i++)
            {
                TextureImporterProperties[ps[i].Name] = ps[i];
            }

            type = typeof(TextureImporterPlatformSettings);
            ps = type.GetProperties();
            for (int i = 0; i < ps.Length; i++)
            {
                TextureImporterProperties[ps[i].Name] = ps[i];
            }
        }

        TextureImporter importer = this.assetImporter as TextureImporter;
        Dictionary<string, string> settings = new Dictionary<string, string>();
        //进行正则匹配
        for (int i = 0; i < AssetsImportSettings.TextureSettings.Length; i++)
        {
            if (string.IsNullOrEmpty(AssetsImportSettings.TextureSettings[i].PathRegex)
                || Regex.Match(importer.assetPath, AssetsImportSettings.TextureSettings[i].PathRegex).Success)
            {
                foreach (var pair in AssetsImportSettings.TextureSettings[i].Settings)
                {
                    settings[pair.Key] = pair.Value;
                }
            }
        }

        foreach (var pair in settings)
        {
            //带.的是平台设置
            if (pair.Key.Contains("."))
            {
                var strs = pair.Key.Split('.');
                TextureImporterPlatformSettings platform = null;
                if (strs[0] != "Default")
                {
                    platform = importer.GetPlatformTextureSettings(strs[0]);
                }
                else
                {
                    platform = importer.GetDefaultPlatformTextureSettings();
                }


                if (SetValue(platform, strs[1], pair.Value, TextureImporterProperties))
                {
                    Debug.Log("[AssetsImporter] 处理 " + importer.assetPath + " : " + pair.Key + " = " + pair.Value);
                    importer.SetPlatformTextureSettings(platform);
                }
            }
            else
            {
                if (SetValue(importer, pair.Key, pair.Value, TextureImporterProperties))
                {
                    Debug.Log("[AssetsImporter] 处理 " + importer.assetPath + " : " + pair.Key + " = " + pair.Value);
                }
            }
          
        }      


    }


    private bool SetValue(object importer, string name, string value, Dictionary<string, PropertyInfo> properties)
    {
        PropertyInfo p;
        bool change = false;
        if (properties.TryGetValue(name, out p))
        {
            try
            {
                if (p.PropertyType == typeof(int))
                {
                    var v = int.Parse(value);
                    if (v != (int)p.GetValue(importer, null))
                    {
                        p.SetValue(importer, v, null);
                        change = true;
                    }
                }
                else if (p.PropertyType == typeof(float))
                {
                    var v = float.Parse(value);
                    if (v != (float)p.GetValue(importer, null))
                    {
                        p.SetValue(importer, v, null);
                        change = true;
                    }
                }
                else if (p.PropertyType.IsEnum)
                {
                    var v = Enum.Parse(p.PropertyType, value);
                    if (!v.Equals(p.GetValue(importer, null)))
                    {
                        p.SetValue(importer, v, null);
                        change = true;
                    }
                }
            }
            catch (Exception e)
            {
                //没有找到该参数
                Debug.LogError("[AssetsImporter] 读取字段失败，请确认是否类型是否对应 " + name + " = " + value + "  " + e);
            }
          
        }
        else
        {
            //没有找到该参数
            Debug.LogError("[AssetsImporter] 未知参数，请确认拼写是否正确 " + name + " = " + value);
        }
      
        return change;
    }    
}
